package com.c78.fz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.c78.fz.mapper.UserMapper;
import com.c78.fz.common.result.Result;
import com.c78.fz.model.dto.LoginUser;
import com.c78.fz.model.entity.User;
import com.c78.fz.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Resource
    UserMapper userMapper;

    @Override
    public Result getUser() {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
        queryWrapper.eq(User::getId, loginUser.getUser().getId());
        User user = userMapper.selectOne(queryWrapper);
        return Result.ok(user);
    }

    @Override
    public Result updPwd(String password,String oldPassword) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = loginUser.getUser();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        //判断旧密码是否正确
        if(!bCryptPasswordEncoder.matches(oldPassword,user.getPassword())){
            return Result.error("旧密码不正确");
        }
        //对密码进行加密
        password = bCryptPasswordEncoder.encode(password);
        if(userMapper.updatePasswordInt(user.getId(),password)>0){
            return Result.ok("修改密码成功,请重新登录");
        }
        return Result.error("修改密码失败");
    }
}
